package com.dmcloud.zuul.filter;

import com.dmcloud.common.constant.SecurityConstants;
import com.dmcloud.zuul.filter.abstractzuul.AbstractPreZuulFilter;
import com.dmcloud.zuul.filter.pojo.TokenInfo;
import com.netflix.zuul.context.RequestContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by xiaodao
 * date: 2019/11/7
 */
//@Component
@Slf4j
public class OauthFilter extends AbstractPreZuulFilter {
    private RestTemplate restTemplate = new RestTemplate();


    @Override
    public int filterOrder() {
        return 1;
    }


    @Override
    public Object cRun()  {
        log.info("安全认证");
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request  =  requestContext.getRequest();

        if(StringUtils.startsWith(request.getRequestURI(),"/token")){
            return null;
        }
        String header = request.getHeader("Authorization");
        if(StringUtils.isEmpty(header)){
            //没有带请求头.继续往下走
            return null;
        }
        //bearer是oauth的也让他走.
        if(!StringUtils.startsWithIgnoreCase(header,"bearer ")){
            return null;
        }
        //这里要校验.校验你的token
        try {
            TokenInfo info = getTokenInfo(header);
            request.setAttribute("tokenInfo",info);
        } catch (Exception e) {
            log.error("获取token 异常",e);
        }

        return success();
    }

    /**
     * 拿着token 去认证服务器去校验
     * @param header
     * @return
     */
    private TokenInfo getTokenInfo(String header){
        String token = StringUtils.substringAfter(header,"bearer ");
        String oauthServiceUrl= SecurityConstants.AUTH_SERVER_URL;
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        httpHeaders.setBasicAuth(SecurityConstants.GATE_WAY_CLIENT_ID,SecurityConstants.GATE_WAY_CLIENT_PASSWORD);

        MultiValueMap<String,String> multiValueMap =new LinkedMultiValueMap<>();
        multiValueMap.add("token",token);

        HttpEntity<MultiValueMap<String,String>> entity =  new HttpEntity<>(multiValueMap,httpHeaders);
        ResponseEntity<TokenInfo> responseEntity =restTemplate.exchange(oauthServiceUrl, HttpMethod.POST,entity,TokenInfo.class);
        log.info("认证服务器返回的结果: "+ responseEntity.getBody().toString());
        return responseEntity.getBody();



    }
}
